<?php
namespace Admin\Controller;
use Think\Controller;
class IndexController extends CommenController {
    /**
     *后台主页
     */
    public function index(){
        $info=M('merchant_role','','XYC');
        $power_db=M('merchant_power','','XYC');
        if($_SESSION['rid']=='99'){
            $top_power=$power_db->WHERE(['level'=>'1','status'=>'1','version'=>'2'])->ORDER("weight asc")->SELECT();
            $next_power=$power_db->WHERE(['level'=>'2','status'=>'1','version'=>'2'])->ORDER("weight asc")->SELECT();
        }else{
            $role=$info->WHERE(['id'=>$_SESSION['rid']])->FIND();
            $top_power=$power_db->WHERE("id in({$role['top_id']}) and level=1 and status=1 and version=2")->ORDER("weight asc")->SELECT();
            $next_power=$power_db->WHERE("id in({$role['next_id']}) and level=2 and status=1  and version=2")->ORDER("weight asc")->SELECT();
        }
        $merchant_msg=M('merchant','','XYC')->WHERE(['shop_identifier'=>$_SESSION['shop_identifier']])->FIND();
        //角色
        $role=explode(',',$_SESSION['rid']);
        $is_kf=0;
        if(in_array('10',$role) || $_SESSION['rid']=='99'){
            $is_kf=1;
        }
        $this->assign(array(
            'top_power'=>$top_power,
            'next_power'=>$next_power,
            'merchant_msg'=>$merchant_msg,
            'is_kf'=>$is_kf
        ));
        $this->display();
    }


    /**
     * 获取余额
     */

    public  function  get_balance(){
        $data=M('merchant','','XYC')->where(['shop_identifier'=>$_SESSION['shop_identifier']])->field('msg_balance,aut_balance,withhold_balance')->find();

        $this->ajaxReturn(['code'=>'1001','data'=>$data]);
    }


    /***
     * @param:
     * @param:公告
     */
    public function notice(){
        $n = I('page', 1);
        $num = 12;
        $page = ($n - 1) * $num;
        $field='content,type,title,ctime,id';
        $where=[];
        $shop_identifier=$_SESSION['shop_identifier'];
//        $where['shop_identifier']=array('1',$_SESSION['shop_identifier'],'or');//显示全部和属于商户的公告
        $where['_string']="shop_identifier='$shop_identifier' or shop_identifier='1'";
        $where['status']='1';
        $count=M('sys_notice','','XYC')->where($where)->count();
        $count=intval($count);
        $notice=M('sys_notice','','XYC')->where($where)->limit($page,$num)->order('ctime desc')->field($field)->select();
        foreach ($notice as $k=>$v){
            $type='';
            switch ($v['type']){
                case 1:  $type='【系统公告】'; break;
                case 2:  $type='【风险警示】'; break;
                case 3:  $type='【产品公告】'; break;
                case 4:  $type='【客服通知】';  break;
            }
            $notice[$k]['ctime']=date('Y-m-d H:i:s',$v['ctime']);
            $notice[$k]['content']=$type.$v['content'];
            $notice[$k]['detail']=$v['content'];
        }
      $tol=ceil($count/$num);
      $this->ajaxReturn(array('code'=>'1001','count'=>$count,'tol'=>$tol,'result'=>$notice));

    }

    /***
     * @param:
     * @param:公告详情
     */
    public function notice_details(){
        $id=I('id');
        $detail=M('sys_notice','','XYC')->where(['id'=>$id])->field('title,content,type,ctime,shop_identifier,aid')->find();
        $detail['ctime']=date('Y-m-d H:i:s',$detail['ctime']);
        $detail['pusher']=M('admin_login','','XYC')->where(['id'=>$detail['aid']])->getField('name');
        $this->assign(array('notice'=>$detail));
        $this->display();

    }


    public function home(){
        $shop_identifier=$_SESSION['shop_identifier'];
        $choose_time=!empty(I('get.time'))?strtotime(I('get.time')):time();
        //总注册人数
        $total_register=M('user','','XYC')->where(['shop_identifier'=>$shop_identifier])->count();
        $data['total_register']=$total_register;

         //总放款金额
        $total_borrow=M('vz_loan','','XYC')->where(['is_success'=>2,'shop_identifier'=>$shop_identifier])->sum('loan_amount');
        $data['total_borrow']=$total_borrow;
        if(empty($total_borrow)){
            $data['total_borrow']=0;
        }

        //总逾期金额
        $total_overdue=M('vz_loan','','XYC')->where(['shop_identifier'=>$shop_identifier,'is_success'=>2,'status'=>3])->sum('loan_amount');
        $data['total_overdue']=$total_overdue;
        if(empty($total_overdue)){
            $data['total_overdue']=0;
        }

        //总订单数
        $total_orders=M('vz_loan','','XYC')->where(['shop_identifier'=>$shop_identifier,'is_success'=>2])->count();
        $data['total_orders']=$total_orders;

       //借款待审核
        $wait_borrow_check=M('vz_loan','','XYC')->where(['shop_identifier'=>$shop_identifier,'status'=>0])->count();
        $data['wait_borrow_check']=$wait_borrow_check;


       //待放款
        $wait_borrow=M('vz_loan','','XYC')->where(['shop_identifier'=>$shop_identifier,'status'=>5])->count();//
        $data['wait_borrow']=$wait_borrow;


       //今日订单数
        $s_time=strtotime(date('Y-m-d',time()));
        $e_time=time();
        $today_order=M('vz_loan','','XYC')->where(['shop_identifier'=>$shop_identifier,'is_success'=>2,'ctime'=>['between',[$s_time,$e_time]]])->count();
        $data['today_order']=$today_order;

        //今日借款金额
        $today_borrow_money=M('vz_loan','','XYC')->where(['shop_identifier'=>$shop_identifier,'is_success'=>2,'ctime'=>['between',[$s_time,$e_time]]])->sum('loan_amount');
        $data['today_borrow_money']=$today_borrow_money;
        if(empty($today_borrow_money)){
            $data['today_borrow_money']=0;
        }

        //综合逾期率
        $overdue_num=M('vz_loan','','XYC')->where(['shop_identifier'=>$shop_identifier,'is_success'=>2,'status'=>3])->sum('loan_amount');
        $overdue_rate=intval($overdue_num/$total_orders,2);
        $data['overdue_rate']=$overdue_rate;

        //当天以及前7天每天的新增人数和通过率
        $time_s=date('Ymd',$choose_time);
        $redis=MycommonController::mk_redis();
        $user_db = M('user', '', 'XYC');//用户表
        $user_examine_db = M('user_examine', '', 'XYC');//用户认证表
        $loan_db= M('vz_loan', '', 'XYC');//订单表
        if(empty($redis->get($time_s.$shop_identifier.RedisPrefixController::VZ_ADD_USER))){

            for ($i = 7; $i >= 0; $i--) {
                //0表示当天
                if ($i == 0) {
                    $date[] = date('Y-m-d',$choose_time);
                    $time = array(strtotime(date('Y-m-d', $choose_time)), strtotime(date('Y-m-d 23:59:59', $choose_time)));
                    $add_user_where['ctime']=array('between',$time);
                    $add_user_where['shop_identifier']=$shop_identifier;
                    $add_user[]=$user_db->WHERE($add_user_where)->COUNT();
                    $over_cert_user_count=$user_examine_db->JOIN("a JOIN user b ON a.user_id=b.id")->WHERE(['b.ctime'=>['between',$time],'b.shop_identifier'=>$shop_identifier])->GROUP('a.user_id')->FIELD('a.user_id')->SELECT();
                    $cert_users=$user_db->WHERE(['ctime'=>['between',$time],'id'=>['in',array_column($over_cert_user_count,'user_id')],'cert_status'=>'2'])->COUNT();
                    $cert_user[]=!empty($cert_users)?$cert_users:0;
                }else{
                    $date[] = date('Y-m-d',strtotime("-{$i} day",$choose_time));
                    $time = array(strtotime(date('Y-m-d', strtotime("-{$i} day",$choose_time))), strtotime(date('Y-m-d 23:59:59', strtotime("-{$i} day",$choose_time)))); //前一天
                    $add_user_where['ctime']=array('between',$time);
                    $add_user_where['shop_identifier']=$shop_identifier;
                    $add_user[]=$user_db->WHERE($add_user_where)->COUNT();
                    $over_cert_user_count=$user_examine_db->JOIN("a JOIN user b ON a.user_id=b.id")->WHERE(['b.ctime'=>['between',$time],'b.shop_identifier'=>$shop_identifier])->GROUP('a.user_id')->FIELD('a.user_id')->SELECT();
                    $cert_users=$user_db->WHERE(['ctime'=>['between',$time],'id'=>['in',array_column($over_cert_user_count,'user_id')],'cert_status'=>'2'])->COUNT();
                    $cert_user[]=!empty($cert_users)?$cert_users:0;
                }
            }

            //当天以及前7天每天的借款金额
            for ($i = 7; $i >= 0; $i--) {
                //0表示当天
                if ($i == 0) {
                    $time = array(strtotime(date('Y-m-d', $choose_time)), strtotime(date('Y-m-d 23:59:59', $choose_time)));
                    $borrow_where['get_time']=array('between',$time);
                    $borrow_where['is_success']=array('eq',2);
                    $borrow_where['shop_identifier']=$shop_identifier;
                    $borrow_m=$loan_db->WHERE($borrow_where)->SUM('loan_amount');
                    $borrow_money[]=!empty($borrow_m)?$borrow_m:'0';
                }else{
                    $time = array(strtotime(date('Y-m-d', strtotime("-{$i} day",$choose_time))), strtotime(date('Y-m-d 23:59:59', strtotime("-{$i} day",$choose_time)))); //前一天
                    $borrow_where['get_time']=array('between',$time);
                    $borrow_where['is_success']=array('eq',2);
                    $borrow_where['shop_identifier']=$shop_identifier;
                    $borrow_m=$loan_db->WHERE($borrow_where)->SUM('loan_amount');
                    $borrow_money[]=!empty($borrow_m)?$borrow_m:'0';
                }
            }

            //当天以及前7天每天的还款金额
            for ($i = 7; $i >= 0; $i--) {
                //0表示当天
                if ($i == 0) {
                    $time = array(strtotime(date('Y-m-d', $choose_time)), strtotime(date('Y-m-d 23:59:59', $choose_time)));
                    $repayment_where['actual_time']=array('between',$time);
                    $repayment_where['status']='2';
                    $repayment_where['shop_identifier']=$shop_identifier;
                    $repayment_m=$loan_db->WHERE($repayment_where)->SUM('loan_amount');
                    $repayment_money[]=!empty($repayment_m)?$repayment_m:0;
                }else{
                    $time = array(strtotime(date('Y-m-d', strtotime("-{$i} day",$choose_time))), strtotime(date('Y-m-d 23:59:59', strtotime("-{$i} day",$choose_time)))); //前一天
                    $repayment_where['actual_time']=array('between',$time);
                    $repayment_where['status']='2';
                    $repayment_where['shop_identifier']=$shop_identifier;
                    $repayment_m=$loan_db->WHERE($repayment_where)->SUM('loan_amount');
                    $repayment_money[]=!empty($repayment_m)?$repayment_m:0;
                }
            }

            $redis->setex($time_s.$shop_identifier.RedisPrefixController::VZ_ADD_USER,3600,json_encode($add_user));
            $redis->setex($time_s.$shop_identifier.RedisPrefixController::VZ_CERT_USER,3600,json_encode($cert_user));
            $redis->setex($time_s.$shop_identifier.RedisPrefixController::VZ_BORROW_MONEY,3600,json_encode($borrow_money));
            $redis->setex($time_s.$shop_identifier.RedisPrefixController::VZ_REPAYMENT_MONEY,3600,json_encode($repayment_money));
            $redis->setex($time_s.$shop_identifier.RedisPrefixController::VZ_DATE,3600,json_encode($date));
        }else{
            $add_user=json_decode($redis->get($time_s.$shop_identifier.RedisPrefixController::VZ_ADD_USER));
            $cert_user=json_decode($redis->get($time_s.$shop_identifier.RedisPrefixController::VZ_CERT_USER));
            $borrow_money=json_decode($redis->get($time_s.$shop_identifier.RedisPrefixController::VZ_BORROW_MONEY));
            $repayment_money=json_decode($redis->get($time_s.$shop_identifier.RedisPrefixController::VZ_REPAYMENT_MONEY));
            $date=json_decode($redis->get($time_s.$shop_identifier.RedisPrefixController::VZ_DATE));
        }

        //待审用户数
//        $wait_check=M('user','','XYC')->where(['shop_identifier'=>$shop_identifier,'cert_status'=>'5'])->count();


//        $wait_certificate=M('certificate','','XYC')->where(['shop_identifier'=>$shop_identifier,'status'=>'1'])->count();

        //用户反馈待处理数
//        $wait_for_feedback=M('user_feedback','','XYC')->join('a join user b on b.id=a.user_id')->where(['a.status'=>0,'b.shop_identifier'=>$shop_identifier])->count();

//        $data=array('wait_check'=>$wait_check,'wait_certificate'=>$wait_certificate,'wait_for_feedback'=>$wait_for_feedback);

        $this->assign(array(
            'date'=>json_encode($date),
            'add_user'=>json_encode($add_user),
            'cert_user'=>json_encode($cert_user),
            'borrow_money'=>json_encode($borrow_money),
            'repayment_money'=>json_encode($repayment_money),
            'data'=>$data
        ));
        $this->display();
    }


    /***
     * 聊天显示
     */
    public function chat(){
        $this->assign(array('shop_identifier'=>$_SESSION['shop_identifier']));
        $this->display();
    }


    /**
     * 设置有效期
     * @return int 秒
     */
    protected function set_expire(){
        $s=date('s');
        if($s>=1 && $s<60){
            return 60*(60-$s);
        }else{
            return 3600;
        }
    }


}